package com.sys.Utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.SocketException;
import java.util.Date;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.springframework.web.multipart.MultipartFile;

public class FileUtils {

	private static String path = "img";
	private static String addr = "120.132.8.64";
	private static int port = 21;
	private static String username = "utest";
	private static String password = "ptest";
	private static FTPClient ftp;
	private static String imgType = "jpg,gif,png,jpeg";
	private static String baseFolder = "/data/img";
	public static String writeFileToHD(byte[] fileData, String fileName) throws Exception {
		File folder = new File(baseFolder);
		if (!folder.exists()) {
			folder.mkdirs();
		}
		File f = new File(folder, fileName);
		f.createNewFile();
		FileOutputStream out = null;
		try {
			out = new FileOutputStream(f);
			out.write(fileData);
			out.flush();
		} catch (Exception e) {
			throw e;
		} finally {
			if (out != null) {
				out.close();
			}
		}
		return f.getAbsolutePath();
	}

	/**
	 * 上传图片
	 * @param file
	 * @return
	 */
	public static String uploadImg(MultipartFile file){
		String type = file.getContentType();
		type = type.substring(type.indexOf("/")+1,type.length());
		if(imgType.indexOf(type)>0){
			connect();
			String name = new Date().getTime()+file.getOriginalFilename();
			try {
				upload(file.getInputStream(),name);
			} catch (Exception e) {
				e.printStackTrace();
				return null;
			}
			return "http://" + addr+ "/" + name;
		}else{
			return null;
		}
	}

	/**
	 * 
	 * @param path
	 *            上传到ftp服务器哪个路径下
	 * @param addr
	 *            地址
	 * @param port
	 *            端口号
	 * @param username
	 *            用户名
	 * @param password
	 *            密码
	 * @return
	 * @throws Exception
	 */
	private static boolean connect() {
		boolean result = false;
		ftp = new FTPClient();
		int reply;
		try {
			ftp.connect(addr, port);
			ftp.login(username, password);
			//上传文件使用二进制形式上传
			ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
			reply = ftp.getReplyCode();
			if (!FTPReply.isPositiveCompletion(reply)) {
				ftp.disconnect();
				return result;
			}
			ftp.changeWorkingDirectory(path);
		} catch (SocketException e) {
			e.printStackTrace();
			return false;
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
		result = true;
		return result;
	}

	/**
	 * 
	 * @param file
	 *            上传的文件或文件夹
	 * @throws Exception
	 */
	private static void upload(InputStream input,String name) throws Exception {
			ftp.storeFile(name, input);
			input.close();
	}
}
